package com.huangsm.book.designmodel.parallel.pcmodel;

import com.sun.xml.internal.bind.v2.runtime.output.Pcdata;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author huang
 * @PACKAGE_NAME com.huangsm.book.designmodel.parallel.pcmodel
 * @PROJECT_NAME concurrence
 * @date 2019/2/19
 */
public class Producer implements Runnable {
    private volatile boolean isRunning = true;
    /**
     * 内存缓冲区
     */
    private BlockingQueue<PCData> queue;
    /**
     * 总数原子性操作
     */
    private static AtomicInteger count = new AtomicInteger();

    private static final int SLEEPTIOME = 1000;

    public Producer(BlockingQueue<PCData> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        PCData pcdata = null;
        Random r = new Random();
        System.out.println("start producer id=" + Thread.currentThread().getId());
        while (isRunning) {
            try {
                Thread.sleep(r.nextInt(SLEEPTIOME));
                //构造任务数据
                pcdata = new PCData(count.incrementAndGet());
                System.out.println(pcdata + "is put into queue");
                if (!queue.offer(pcdata, 2, TimeUnit.SECONDS)) {
                    System.out.println("failed to put data" + pcdata);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
        }
    }

    public void stop() {
        isRunning = false;
    }
}
